package com.taokatao.cardmee.business.login;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.common.widget.TitleLayout;
import com.taokatao.cardmee.db.model.User;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 登录或注册的界面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.l_title) TitleLayout layTitle;
    @BindView(R.id.t_auth_query) TextView tAuthQuery;
    @BindView(R.id.e_account) EditText eAccount;
    @BindView(R.id.e_auth) EditText eAuth;
    @BindView(R.id.t_submit) TextView tSubmit;
    @BindView(R.id.t_tip) TextView tTip;

    private static final int DEFAULT_COUNTDOWN = 60;
    private int countdownTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        String lastLogoutUserTel = Utils.spReadString(C.sp.LAST_LOGOUT_USER_TEL);

        if (TextUtils.isEmpty(lastLogoutUserTel)) {
            tTip.setVisibility(View.VISIBLE);
        } else {
            tTip.setVisibility(View.INVISIBLE);
            eAccount.setText(lastLogoutUserTel);
        }

        Utils.throttleFirstClick(tAuthQuery, this);
        Utils.throttleFirstClick(tSubmit, this);
    }

    @Override
    public void onClick(View v) {
        if (v == tSubmit) {
            String inputPhone = eAccount.getText().toString().trim();
            String inputAuthCode = eAuth.getText().toString().trim();
            if (TextUtils.isEmpty(inputPhone) || inputPhone.length() < 11) {
                Utils.showToast("手机号码错误");
            } else if (TextUtils.isEmpty(inputAuthCode) || inputAuthCode.length() < 6) {
                Utils.showToast("验证码错误");
            } else {
                Utils.onMobEvent(this, "phoneLogin");
                requestLogin();
            }
        } else if (v == tAuthQuery) {
            String inputPhone = eAccount.getText().toString().trim();
            if (TextUtils.isEmpty(inputPhone) || inputPhone.length() < 11) {
                Utils.showToast("手机号码错误");
            } else {
                requestObtainAuthCode(inputPhone);
            }
        }
    }

    private void requestLogin() {
        long currUuid = 0;
        if (App.i().getCurrUser() != null) {
            currUuid = App.i().getCurrUser().getUuid();
        }
        if (currUuid < 1) {
            requestRegister();
        } else {
            final String userTel = eAccount.getText().toString().trim();
            String randomCode = eAuth.getText().toString().trim();
            ApiManager.i().login(this, currUuid, userTel, randomCode, new SubscriberAdapter<RespWrapper<User>>() {
                @Override
                public void onNext(RespWrapper<User> o) {
                    super.onNext(o);
                    if (o.code == C.http.RESULT_CODE_SUCCESS) {
                        User currUser = o.decode(User.class);
                        currUser.setUserTel(userTel);
                        App.i().setCurrUser(currUser);
                        finish();
                    }
                }
            }.showProgress(this));
        }
    }

    private void requestRegister() {
        ApiManager.i().register(this, new SubscriberAdapter<RespWrapper<User>>() {
            @Override
            public void onNext(RespWrapper<User> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    User currUser = o.decode(User.class);
                    App.i().setCurrUser(currUser);
                    requestLogin();
                }
            }
        }.showProgress(this));
    }

    private void requestObtainAuthCode(String inputPhone) {
        tAuthQuery.setText("获取中");
        tAuthQuery.setEnabled(false);
        ApiManager.i().obtainAuthCode(this, inputPhone, new SubscriberAdapter<RespWrapper<Object>>() {
            @Override
            public void onNext(RespWrapper<Object> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    countdownTime = DEFAULT_COUNTDOWN;
                    refreshAuthCodeCountdown();
                } else {
                    tAuthQuery.setText("获取验证码");
                    tAuthQuery.setEnabled(true);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                tAuthQuery.setText("获取验证码");
                tAuthQuery.setEnabled(true);
            }
        });
    }


    /**
     * 验证码短信获取重置倒计时 默认为60秒 {@link LoginActivity#DEFAULT_COUNTDOWN}
     */
    private void refreshAuthCodeCountdown() {
        tAuthQuery.setText(countdownTime + "s后重新获取");
        tAuthQuery.removeCallbacks(runRefreshAuthCountdown);
        tAuthQuery.postDelayed(runRefreshAuthCountdown, 1000);
    }

    private Runnable runRefreshAuthCountdown = new Runnable() {
        @Override
        public void run() {
            countdownTime--;
            if (countdownTime <= 0) {
                tAuthQuery.setText("获取验证码");
                tAuthQuery.setEnabled(true);
            } else {
                refreshAuthCodeCountdown();
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tAuthQuery.removeCallbacks(runRefreshAuthCountdown);
    }
}
